package com.scuola.scuoladocente;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class classeTab extends Activity {
	
	private ListView lv;
	private int[] assenze;
	private String insert = "";
	private String delete = "";
	private JSONArray parsedList = null;
	private JSONParser parser = new JSONParser();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classe_tab);
        
        lv = (ListView)findViewById(R.id.classeTab_lv);
        ArrayList<String> lvItems = new ArrayList<String>();
        
        try {
        	AsyncTask<Void, Void, String> getAlumniByClassIdResponse = new getAlumniByClassId().execute();
			parsedList = (JSONArray) parser.parse(getAlumniByClassIdResponse.get());
			
			for(int i = 0; i < parsedList.size(); i++ ){
				JSONObject obj = (JSONObject) parser.parse(parsedList.get(i).toString());
				lvItems.add(obj.get("cognome").toString()+" "+obj.get("nome").toString());
			}
			
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, lvItems);
			lv.setAdapter(adapter);
			
			AsyncTask<Void, Void, String> getAssenzeByClassAndDateResponse = new getAssenzeByClassAndDate().execute();
			JSONArray assenzeParsedList = (JSONArray) parser.parse(getAssenzeByClassAndDateResponse.get());
			
			assenze = new int[parsedList.size()];
			for (int i = 0; i < parsedList.size(); i++){
				int presente = 0;
				JSONObject obj = (JSONObject) parser.parse(parsedList.get(i).toString());
				for (int j = 0; j < assenzeParsedList.size(); j++){
					JSONObject objAssenze = (JSONObject) parser.parse(assenzeParsedList.get(j).toString());
					if(obj.get("id").toString().equals(objAssenze.get("idstudente").toString())){
						presente = 1;
					}
				}
				assenze[i] = presente;
			}
			
			for(int i = 0; i < assenze.length; i++){
				if(assenze[i] == 1){
					lv.setItemChecked(i, true);
				}
			}
			
			DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
			Date date = new Date();
			Toast msg = Toast.makeText(getApplicationContext(), "Assenze del giorno: "+dateFormat.format(date).toString(), Toast.LENGTH_SHORT);
			msg.show();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    private class getAlumniByClassId extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... arg0) {
			try{	
				LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
				hm.put("classId", getIntent().getStringExtra("idclasse"));
				String strResponse = operations.wsCall("getAlumniByClassId", hm).toString();
				return strResponse;
				
			} catch (Exception e) {
				System.err.println("getAlumniByClassId errore (Exception)");
				e.printStackTrace();
				return null;
			}
		
		}
    }
    
    private class getAssenzeByClassAndDate extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... arg0) {
			try{	
				LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date();
				hm.put("giorno", dateFormat.format(date).toString());
				hm.put("idclasse", getIntent().getStringExtra("idclasse"));
				String strResponse = operations.wsCall("getAssenzeByClassAndDate", hm).toString();
				return strResponse;
				
			} catch (Exception e) {
				System.err.println("getAssenzeByClassAndDate errore (Exception)");
				e.printStackTrace();
				return null;
			}
		
		}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_classe_tab, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.Salva:
            	String res = SalvaAssenze();
            	String messaggio = null;
            	if (res.equals("OK")){
	            	messaggio = "Assenze Salvate";
            	}else{
            		messaggio = "Assenze non salvate correttamente. Riprova!";
            	}
            	Toast msg = Toast.makeText(getApplicationContext(), messaggio, Toast.LENGTH_SHORT);
            	msg.show();
                break;
        }
		return true;
    }
    
    public String SalvaAssenze(){
    	try{
    		insert = "";
    		delete = "";
	    	SparseBooleanArray selectedItems = lv.getCheckedItemPositions();
	    	for(int i = 0; i < lv.getCount(); i++){
	    		if((assenze[i] == 1) && (selectedItems.get(i) == false)){
	    			JSONObject obj = (JSONObject) parser.parse(parsedList.get(i).toString());
	    			delete = delete + obj.get("id")+"|";
	    			assenze[i] = 0;
	    		}else if((assenze[i] == 0) && (selectedItems.get(i) == true)){
	    			JSONObject obj = (JSONObject) parser.parse(parsedList.get(i).toString());
	    			insert = insert + obj.get("id")+"|";
	    			assenze[i] = 1;
	    		}
	    	}
	    	AsyncTask<Void, Void, String> setAssentiResponse = new setAssenti().execute();
    		String res = (String) setAssentiResponse.get();
	    	return res;
    	}catch(Exception e){
    		e.printStackTrace();
    		return "ERROR";
    	}
    }
    
    private class setAssenti extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... arg0) {
			try{	
				LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
				hm.put("insert", insert);
				hm.put("delete", delete);
				hm.put("idclasse", getIntent().getStringExtra("idclasse"));
				String strResponse = operations.wsCall("setAssenti", hm).toString();
				return strResponse;
				
			} catch (Exception e) {
				System.err.println("getAlumniByClassId errore (Exception)");
				e.printStackTrace();
				return null;
			}
		
		}
    }
}
